var express = require('express');
var router = express.Router();
let jwt = require('jsonwebtoken')
let userServer = require('../service/userServive');
let userTypesServer = require("../service/typeService");
let typeMenusServer = require("../service/typeMenuService");
let typeRoutersServer = require("../service/typeRouterService");

let projectService = require('../service/projectService');
let developerService = require('../service/developerService');
let bugTypesService = require('../service/bugTypesService');
/* GET users listing. */
router.get('/', function (req, res, next) {
    res.send('respond with a resource');
});



// router.post('/add', async (req, res, next) => {
//     console.log(req.body)
//     let { userid, project, projectname, requirement, start, extend, type = 0 } = req.body
//     let params = { project, projectname, requirement, start, extend, type }

//     jwt.verify(req.headers.token, 'abc', async (err, info) => {
//         if (!err) {
//             if (userid) {
//                 params.userid = userid
//             }
//             let result = await projectService.add({ username: info.username, ...params });
//             console.log(result)
//             if (result.length) {
//                 res.send({
//                     code: 200,
//                     msg: "添加成功",
//                     data: result
//                 })
//             } else {
//                 res.send({
//                     code: 203,
//                     msg: "添加失败",
//                 })
//             }
//         } else {
//             res.send({
//                 code: 203,
//                 msg: "token过期，请重新登录",
//             })
//         }

//     })

// })

// 添加
router.post('/add', async (req, res, next) => {
    let { reason, start, bugtypeid, userid, type = 2, extend, projectid } = req.body
    jwt.verify(req.headers.token, 'abc', async (err, info) => {
        if (!err) {
            let project = await projectService.query({ _id: projectid })
            let bugType = await bugTypesService.query({ _id: bugtypeid })
            let username = await userServer.query({ _id: userid })
            let params = { demoid: info.id, demoname: info.username, reason, start, bugtypeid, bugType: bugType[0].type, userid, username: username[0].username, type, projectname: project[0].project, projectid }
            if (extend) {
                params.extend = extend
            }
            let result = await developerService.add(params);

            if (result.length) {
                res.send({
                    code: 200,
                    msg: "添加成功",
                    data: result
                })
            } else {
                res.send({
                    code: 203,
                    msg: "添加失败",
                })
            }
        } else {
            res.send({
                code: 203,
                msg: "token过期，请重新登录",
            })
        }

    })

})

// 列表查询
router.get('/query', (req, res, next) => {
    let { pageindex = 1, pageNum = 5 } = req.query
    let tokenData = req.headers.token
    jwt.verify(tokenData, 'abc', async (err, info) => {
        if (!err) {
            let result = await developerService.query({ demoid: info.id }, (pageindex - 1) * pageNum, pageNum * 1)
            let total = await developerService.count({ demoid: info.id })
            let bugTypeList = await bugTypesService.query({});
            let projectList = await projectService.query({ userid: info.pid })
            res.json({
                code: 200,
                msg: "查询成功",
                data: result,
                total,
                bugTypeList,
                projectList
            })
        } else {
            res.json({
                code: 200,
                msg: "token过期，请重新登录",
            })
        }
    })

})

// 修改
router.patch('/update', async (req, res, next) => {
    let { _id, type, end, reason, userid } = req.body
    if (reason) {
        let params = {reason}
        if (userid) {
            let username = await userServer.query({ _id: userid })
            params.username = username[0].username
            params.userid = userid
        }
        let result = await developerService.updated({ _id }, { $set: params });
        if (result.nModified) {
            let result2 = await developerService.query({ _id })
            res.send({
                code: 200,
                msg: "修改成功",
                data: result2
            })
        } else {
            res.send({
                code: 203,
                msg: "修改失败",
            })
        }

    } else {
        let result = await developerService.updated({ _id }, { $set: { type, end } });
        if (result.nModified) {
            res.send({
                code: 200,
                msg: "审批成功",
                data: result
            })
        } else {
            res.send({
                code: 203,
                msg: "该请求已处理",
            })
        }
    }


})


// 列表查询
router.get('/teacherquery', (req, res, next) => {
    let { pageindex = 1, pageNum = 5, type } = req.query
    let tokenData = req.headers.token
    jwt.verify(tokenData, 'abc', async (err, info) => {
        let pid = info.id;
        let childList = await userServer.query({ pid })
        let result1 = childList.map(item => item._id)
        let params = { userid: { $in: result1 } }
        if (!err) {
            if (type) {
                params.type = type
            }
            let result = await developerService.query(params, (pageindex - 1) * pageNum, pageNum * 1)
            let total = await developerService.totalquery(params)
            res.json({
                code: 200,
                msg: "查询成功",
                data: result,
                total
            })
        } else {
            res.json({
                code: 200,
                msg: "token过期，请重新登录",
            })
        }
    })

})


// 生成统计表
router.get("/group", (req, res, next) => {
    let token = req.headers.token;
    jwt.verify(token, "abc", async (err, info) => {
        if (!err) {
            let pid = info.id; //老师的编号 也就是登录人的编号
            let result = await userServer.query({ pid });
            let studentList = result.map((item) => item._id + ""); //这个老师的所有学生的编号

            let key = req.query.key // 统计表关键词
            let result2 = await developerService.group(
                { userid: { $in: studentList } },
                key
            );

            res.json({
                code: 200,
                msg: "分组统计",
                data: result2,
            });

        } else {
            res.json({
                code: 203,
                msg: "token已过期，请重新登录",
                data: err,
            });
        }
    });
});


// 修改
router.patch('/update', async (req, res, next) => {
    let { _id, type } = req.body
    let result = await leavesServer.update({ _id }, { $set: { type } });

    if (result.nModified) {
        res.send({
            code: 200,
            msg: "审批成功",
            data: result
        })
    } else {
        res.send({
            code: 203,
            msg: "该请求已处理",
        })
    }

})



// 删除
router.delete('/del', async (req, res, next) => {
    let { _id } = req.body
    let result = await userServer.del({ _id });
    if (result.deletedCount) {
        res.send({
            code: 200,
            msg: "删除成功",
            data: result
        })
    } else {
        res.send({
            code: 200,
            msg: "删除失败",
        })
    }

})

module.exports = router;
